//
//  CLSubmitDataVC.m
//  CareLink
//
//  Created by 刘家强 on 16/8/19.
//  Copyright © 2016年 Seven Team. All rights reserved.
//

#import "CLSubmitDataVC.h"
#import "CLSubmitDataView.h"
#import "IMJIETagFrame.h"
#import "IMJIETagView.h"
#import "MKComposePhotosView.h"
#import "MKMessagePhotoView.h"
#import "PlaceholderTextView.h"
#import "UMSocialSnsService.h"
#import <SMS_SDK/SMSSDK.h>

#define KWIDTH [UIScreen mainScreen].bounds.size.width
#define kWindowWidth [UIScreen mainScreen].bounds.size.width
#define kTextBorderColor RGBCOLOR(227, 224, 216)
#undef RGBCOLOR
#define RGBCOLOR(r, g, b) [UIColor colorWithRed:r / 255.0 green:g / 255.0 blue:b / 255.0 alpha:1]
#define UmengAppkey @"53290df956240b6b4a0084b3"

@interface CLSubmitDataVC () <MKMessagePhotoViewDelegate, UITextFieldDelegate, IMJIETagViewDelegate, UITextViewDelegate, UIScrollViewDelegate>

@property (strong, nonatomic) IBOutlet UIScrollView *scrollView;
@property (nonatomic, weak) CLSubmitDataView *xibView;
@property (nonatomic, assign) float frameX;
@property (nonatomic, strong) MKMessagePhotoView *photosView;
@property (nonatomic, strong) NSArray *topTagArr;
@property (nonatomic, strong) NSArray *bottonTagArr;
@property (nonatomic, strong) PlaceholderTextView *textView;
@property (nonatomic, strong) UIImage *image;

@end

@implementation CLSubmitDataVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    //    [self loadInfo];

    self.scrollView.delegate = self;

    // 添加image通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(typeButtonClick:) name:@"image" object:nil];
    // 关闭滚动条的滚动效果
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self loadXib];
    [self setUpPhotosView];
    [self setupUI];
    [self loadAutoTopFrame];
    [self loadAutoBottonFrame];
    [self loadTextView];
    self.xibView.submitClickBlock = ^{

        /**
         
         [SMSSDK commitVerificationCode:self.passwordTextField.text phoneNumber:self.keyStr zone:@"86" result:^(NSError *error) {
         NSLog(@"%@---%@",self.passwordTextField.text,self.keyStr);
         if (!error) {
         NSLog(@"成功");
         UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"" message:@"验证成功" preferredStyle:UIAlertControllerStyleAlert];
         
         [self presentViewController:alertView animated:YES completion:^{
         [NSThread sleepForTimeInterval:2.0];
         [self dismissViewControllerAnimated:YES completion:^{
         //成功之后执行
         [[NSUserDefaults standardUserDefaults] setObject:@"席小凡" forKey:@"nickName"];
         [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"loginState"];
         [self.navigationController popToRootViewControllerAnimated:YES];
         }];
         }];
         }else{
         NSLog(@"%@",error);
         
         [MBProgressHUD showError:@"验证码错误" toView:self.navigationController.view];
         }
         }];
         
         ------------------------------------------------------
         
         [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:self.accountTextField.text zone:@"86" customIdentifier:nil result:^(NSError *error) {
         if (!error) {
         NSLog(@"获取验证码成功");
         UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"获取成功" preferredStyle:UIAlertControllerStyleAlert];
         [self presentViewController:alertController animated:YES completion:^{
         [NSThread sleepForTimeInterval:2.0];
         [self.navigationController dismissViewControllerAnimated:YES completion:nil];
         }];
         } else {
         NSLog(@"%@",error);
         UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"获取失败,请重新获取" preferredStyle:UIAlertControllerStyleAlert];
         [self presentViewController:alertController animated:YES completion:^{
         [NSThread sleepForTimeInterval:1.0];
         [self dismissViewControllerAnimated:YES completion:nil];
         }];
         }

         
         */

        //        [SMSSDK commitVerificationCode:@"18004510851" phoneNumber:<#(NSString *)#> zone:<#(NSString *)#> result:<#^(NSError *error)result#>];
        //
        //        [SMSSDK getVerificationCodeByMethod:SMSGetCodeMethodSMS phoneNumber:@"18004510851" zone:@"86" customIdentifier:nil result:^(NSError *error) {
        //            if (error != nil) {
        //                NSLog(@"成功");
        //            }
        //        }];

        //        NSString *shareText = @"友盟社会化组件可以让移动应用快速具备社会化分享、登录、评论、喜欢等功能，并提供实时、全面的社会化数据统计分析服务。 http://www.umeng.com/social";             //分享内嵌文字
        //        //    UIImage *shareImage = [UIImage imageNamed:@"UMS_social_demo"];          //分享内嵌图片
        //        UIImage *shareImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"UMS_social_demo" ofType:@"png"]];
        //        //调用快速分享接口
        //        [UMSocialSnsService presentSnsIconSheetView:self
        //                                             appKey:UmengAppkey
        //                                          shareText:shareText
        //                                         shareImage:shareImage
        //                                    shareToSnsNames:nil
        //                                           delegate:self];

        UIAlertController *vc;
        // 尝试创建 alertController对象
        if (self.weakDay != nil) {
            vc = [UIAlertController alertControllerWithTitle:@"用户信息" message:[NSString stringWithFormat:@"疾病类型:脑残\n预约医生:老宋\n就诊时间:2016-%@", self.weakDay] preferredStyle:UIAlertControllerStyleAlert];
        } else {
            vc = [UIAlertController alertControllerWithTitle:@"用户信息" message:@"疾病类型:脑残\n预约医生:老宋\n就诊时间:2015.6.6" preferredStyle:UIAlertControllerStyleAlert];
        }

        //    UIAlertController* vc = [UIAlertController alertControllerWithTitle:@"title" message:@"message" preferredStyle:UIAlertControllerStyleAlert];

        // 创建action

        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
            [SVProgressHUD setMinimumDismissTimeInterval:2.5];
            [SVProgressHUD showWithStatus:@"正在发送"];
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD showSuccessWithStatus:@"发送成功~"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];

                    CLDataManager *manager = [CLDataManager sharedManager];

                    CLDataModel *model = [[CLDataModel alloc] init];

                    model.symptomDes = self.textView.text;
                    model.diseaseTypeparameter = self.diseaseStatus[@"diseaseSubject"];
                    model.diseaseDetail = nil;
                    model.image = self.image;
                    model.time = [self loadDate];

                    [manager.dataArr addObject:model];
                    // 创建对象
                    CLData *data = [CLData new];

                    // 赋值
                    data.symptomDes = self.textView.text;
                    data.diseaseTypeparameter = self.diseaseStatus[@"diseaseSubject"];
                    data.diseaseDetail = nil;

                    //                    self.image
                    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@", [self loadDate]]];    // 保存文件的名称
                    BOOL result = [UIImagePNGRepresentation(self.image) writeToFile:filePath atomically:YES];                                            //

                    if (result == true) {
                        data.imageStr = filePath;
                    }
                    data.time = [self loadDate];

                    // 获取默认的 Realm 实例
                    RLMRealm *realm = [RLMRealm defaultRealm];
                    // 每个线程只需要使用一次即可

                    // 通过事务将数据添加到 Realm 中
                    [realm beginWriteTransaction];
                    [realm addObject:data];
                    [realm commitWriteTransaction];

                    [self.navigationController popToRootViewControllerAnimated:YES];
                });
            });

        }];

        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *_Nonnull action) {
            NSLog(@"handler3");
        }];

        // 添加action
        [vc addAction:action1];
        [vc addAction:action2];

        // 显示
        [self presentViewController:vc animated:YES completion:nil];
    };
}

- (void)loadTextView {
    //    self.xibView.textField.delegate = self;
    //    // 键盘上没有Done键的时候，如何将return更改成Done:
    //
    //    self.xibView.textField.returnKeyType = UIReturnKeyDone;

    self.textView.returnKeyType = UIReturnKeyDone;
    [self.xibView.textView addSubview:self.textView];
    //    self.textView.frame = self.xibView.textView.frame;
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.xibView.textView);
    }];
}

- (void)setupUI {
    // 就诊时间
    if (self.weakDay != nil) {
        self.xibView.timeLabel.text = [@"就诊时间:2016-" stringByAppendingString:self.weakDay];
    }

    // 并发症状
    if (self.diseaseStatus != nil) {
        //        self.xibView.diseaseStatus.text
        NSArray *arr = self.diseaseStatus[@"complications"];

        NSMutableString *str = [NSMutableString string];

        [arr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
            [str appendFormat:@"%@ ", obj];
        }];
        self.xibView.diseaseStatus.text = str.copy;

        // 症状

        self.xibView.diseaseLabel.text = [self.diseaseStatus[@"diseaseSubject"] stringByAppendingString:@" 已确诊"];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
//当点击键盘上return按钮的时候调用
{
    //代理记录了当前正在工作的UITextField的实例，因此你点击哪个UITextField对象，形参就是哪个UITextField对象
    [textField resignFirstResponder];    //键盘回收代码
    return YES;
}

- (void)loadXib {
    CLSubmitDataView *xibView = [[UINib nibWithNibName:@"CLSubmitData" bundle:nil] instantiateWithOwner:self options:0].firstObject;

    [self.scrollView addSubview:xibView];

    // 全局化控件
    self.xibView = xibView;
}

- (void)viewDidLayoutSubviews {
    self.scrollView.contentSize = CGSizeMake(kWindowWidth, 720);
    //    [self.xibView mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.edges.equalTo(self.scrollView);
    //    }];
    CGRect rect = self.scrollView.frame;
    rect.size.height = 720;
    rect.origin.y = 0;

    self.xibView.frame = rect;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:NO];
}

#pragma mark -相册视图
- (void)setUpPhotosView {
    if (!self.photosView) {
        self.photosView = [[MKMessagePhotoView alloc] initWithFrame:CGRectMake(0, 270, KWIDTH, 80)];
        [self.scrollView addSubview:self.photosView];

        self.photosView.delegate = self;
        self.photosView.userInteractionEnabled = true;
    }

    // 相机直接设置frame
    self.photosView.frame = CGRectMake(0, 550, kWindowWidth, 100);
}

// 相机的两个代理方法
// 实现代理方法
- (void)addPicker:(UIImagePickerController *)picker {
    [self presentViewController:picker animated:YES completion:nil];
}

- (void)addUIImagePicker:(UIImagePickerController *)picker {
    [self presentViewController:picker animated:YES completion:nil];
    self.modalPresentationStyle = UIModalPresentationOverCurrentContext;
}

// 增加上部标签
- (void)loadAutoTopFrame {
    self.view.backgroundColor = UIColorRGBA(238, 238, 238, 1);

    NSArray *array = @[ @[ @"视力下降", @"头痛", @"面部麻木", @"下颚歪斜", @"吞咽困难", @"面部麻木", @"下颚歪斜" ], @[ @"关节炎", @"化脓性关节炎", @"传染病和寄生虫引起的关节炎", @"反应性关节病", @"痛风", @"缺铁性贫血1" ], @[ @"经常性心慌", @"气短", @"胸闷", @"干活动时加重", @"胸闷偶有刺痛感", @"过性心绞痛" ] ][self.cellNum];
    self.topTagArr = array;
    IMJIETagFrame *frame = [[IMJIETagFrame alloc] init];
    frame.tagsMinPadding = 4;
    frame.tagsMargin = 10;
    frame.tagsLineSpacing = 10;
    frame.tagsArray = array;

    IMJIETagView *tagView = [[IMJIETagView alloc] initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, frame.tagsHeight)];
    tagView.clickbool = YES;
    tagView.borderSize = 1;
    tagView.clickborderSize = 1;
    tagView.tagsFrame = frame;
    //    tagView.clickBackgroundColor = [UIColor greenColor];
    tagView.clickTitleColor = [UIColor colorWithHex:0x22BBB7];
    tagView.clickStart = 1;
    //    tagView.clickString = @"华语";//单选  tagView.clickStart 为0
    //    tagView.clickArray = @[@"误解向",@"我们仍未知道那天所看见的花的名字"];//多选 tagView.clickStart 为1
    tagView.UserArr = array;

    tagView.delegate = self;
    [self.xibView.topTag addSubview:tagView];
}

// 增加底部标签
- (void)loadAutoBottonFrame {
    self.view.backgroundColor = UIColorRGBA(238, 238, 238, 1);

    NSArray *array = @[ @"有家族病史", @"吸烟", @"饮酒" ];
    //    self.bottonTagArr = array;
    IMJIETagFrame *frame = [[IMJIETagFrame alloc] init];
    frame.tagsMinPadding = 4;
    frame.tagsMargin = 10;
    frame.tagsLineSpacing = 10;
    frame.tagsArray = array;

    IMJIETagView *tagView = [[IMJIETagView alloc] initWithFrame:CGRectMake(80, 22, SCREEN_WIDTH, frame.tagsHeight)];
    tagView.clickbool = YES;
    tagView.borderSize = 1;
    tagView.clickborderSize = 1;
    tagView.tagsFrame = frame;
    //    tagView.clickBackgroundColor = [UIColor greenColor];
    tagView.clickTitleColor = [UIColor colorWithHex:0x22BBB7];
    tagView.clickStart = 1;
    //    tagView.clickString = @"华语";//单选  tagView.clickStart 为0
    //    tagView.clickArray = @[@"误解向",@"我们仍未知道那天所看见的花的名字"];//多选 tagView.clickStart 为1
    //    tagView.UserArr = array;

    tagView.delegate = self;
    [self.xibView.bottonTag addSubview:tagView];
}

#pragma mark 选中

// 标签点击后的回调
- (void)IMJIETagViewWithUserArr:(NSArray *)userArr withTagArr:(NSArray *)tagArray {
    if (self.topTagArr == userArr) {
        NSLog(@"%@", tagArray);
    } else {
        NSLog(@"%@", tagArray);
    }
}

// 添加文本输入框
- (PlaceholderTextView *)textView {
    if (!_textView) {
        _textView = [[PlaceholderTextView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 40, 100)];
        _textView.backgroundColor = [UIColor whiteColor];
        _textView.delegate = self;
        _textView.font = [UIFont systemFontOfSize:14.f];
        _textView.textColor = [UIColor blackColor];
        _textView.textAlignment = NSTextAlignmentLeft;
        _textView.editable = YES;
        _textView.layer.cornerRadius = 4.0f;
        _textView.layer.borderColor = kTextBorderColor.CGColor;
        _textView.layer.borderWidth = 0.5;
        _textView.placeholderColor = RGBCOLOR(0x89, 0x89, 0x89);
        _textView.placeholder = @"   请详细描述您的病情，病症描述包括患病时间，症状，服用药物，手术或其他治疗情况输入(10到200字)...";
    }

    return _textView;
}

//把回车键当做退出键盘的响应键  textView退出键盘的操作
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if ([@"\n" isEqualToString:text] == YES) {
        [textView resignFirstResponder];

        return NO;
    }

    return YES;
}

//-(void)IMJIETagView:(NSArray *)tagArray{
//
//    NSLog(@"%p", tagArray);
//
//    NSLog(@"%@",tagArray);
//}

// 城市按钮点击
- (void)typeButtonClick:(id)sender {
    //    NSLog(@"%@",[sender object]);
    UIImage *image = [sender object];

    self.image = image;
}

// 获取时间
- (NSString *)loadDate {
    // 这个是NSDate类型的日期，所要获取的年月日都放在这里；
    NSDate *date = [NSDate date];

    // 获取当前时间
    NSCalendar *cal = [NSCalendar currentCalendar];

    //这句是说你要获取日期的元素有哪些。获取年就要写NSYearCalendarUnit，获取小时就要写NSHourCalendarUnit，中间用|隔开；
    unsigned int unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitHour | NSCalendarUnitDay | NSCalendarUnitMinute | NSCalendarUnitSecond;

    NSDateComponents *d = [cal components:unitFlags fromDate:date];    //把要从date中获取的unitFlags标示的日期元素存放在NSDateComponents类型的d里面；
    //然后就可以从d中获取具体的年月日了；
    NSString *time = [NSString stringWithFormat:@"%ld-%ld-%ld %ld:%ld:%ld", d.year, d.month, d.day, d.hour, d.minute, d.second];

    NSLog(@"%@", time);
    return time;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

#pragma mark - 懒加载

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
